<template>
  <div :class="{'mobile-detail-wrap mobile-el-form':showMobilePage}">
    <template>
      <div v-if="status === 1" class="customer">
        <div class="detail-top-container mobile-header">
          <div :style="showMobilePage?{paddingLeft: '40px'}:''" class="title">{{ detailData.reportName }}</div>
          <div style="flex: 1;"/>
          <ListHeader />
        </div>
        <div class="return-detail min-fill-page no-margin small-padding">
          <el-row :gutter="20" class="detail-info">
            <el-col :span="6">
              <div class="detail-info-item">
                <span class="info-item-title">订单封账月份：</span>
                <span>{{ detailData.orderSealMonthStart / 1000 | standardFormatMonth('YYYY/MM') }}-{{ detailData.orderSealMonthEnd / 1000 | standardFormatMonth('YYYY/MM') }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-info-item">
                <span class="info-item-title">流水到账月份：</span>
                <span>{{ detailData.financeSealMonthStart / 1000 | standardFormatMonth('YYYY/MM') }}-{{ detailData.financeSealMonthEnd / 1000 | standardFormatMonth('YYYY/MM') }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-info-item">
                <span class="info-item-title">核销封账月份：</span>
                <span>{{ detailData.writeOffSealMonthStart / 1000 | standardFormatMonth('YYYY/MM') }}-{{ detailData.writeOffSealMonthEnd / 1000 | standardFormatMonth('YYYY/MM') }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-info-item">
                <span class="info-item-title">类型：</span>
                <span>{{ detailData.returnType | returnTypeStatus }}</span>
              </div>
            </el-col>
          </el-row>
          <dataDisplay v-loading="dataLoading" v-if="returnData" :data-list="dataList" :style="`margin-bottom: ${showMobilePage?'12px':'20px'};`" type="oneCell" />
          <div v-if="!showMobilePage" class="filter-input-box">
            <FilterInput ref="filterInput" v-model="paramsData" :drawer-size="800" :filter-list="filterList" line-feed show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" />
            <div :class="{'table-top-opeator-bar':!showMobilePage,'mobile-operate':showMobilePage}">
              <btnGroup
                ref="btnGroupRef"
                :list="[
                  { label:'导出', exportApi:'admin/return/detail/export', exportName:'导出回款报表', beforeExport: beforeExport, type: 'export' },
                ]"
              />
              <el-button
                v-if="hasRouteAuth('crm:return:create')"
                size="small"
                type="primary"
                style="margin-left: 10px;"
                @click="handleReset">
                重设报表
              </el-button>
            </div>
          </div>
          <div v-loading="loading" style="min-height: 110px;">
            <u-table
              v-if="list.items.length > 0"
              ref="customerTableRef"
              :data="list.items"
              :border="true"
              :row-height="49"
              :height="setTableHeight"
              :row-class-name="(data) => tableRowClassName(data)"
              beautify-table
              header-drag-style
              use-virtual
              class="fb-table"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              header-cell-class-name="order-data-header-cell"
              fit
              hightlight-current-row
              @sort-change="sortMethod"
              @select="selectTable"
              @select-all="selectTable">
              <u-table-column :fixed="showMobilePage?false:'left'" align="center" type="selection" width="50"/>
              <u-table-column align="left" label="编号" width="60" fixed>
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.customerId" />
                </template>
              </u-table-column>
              <u-table-column :fixed="showMobilePage?false:'left'" align="left" label="客户名称" min-width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.customerName" is-can-click @handelClick="toCustomer(scope.row)" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="客户类型" min-width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.customerType | clientStatusFilter" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="销售" min-width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.sale" />
                </template>
              </u-table-column>
              <u-table-column
                v-for="item in columnList"
                :key="item.id"
                :label="item.title"
                :prop="item.field"
                :sortable="sortableValue(item.field)"
                :width="getWidth(item.title)"
                align="right"
                min-width="150">
                <template slot-scope="scope">
                  <div
                    v-if="scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)] && (scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)].amount || scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)].amount === 0)"
                    :class="item.field !== 'owePrice' && scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)].amount !== 0 && 'link'"
                    @click="showDetail(scope.row.id, scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)])">
                    <PriceColumn
                      :real-val="scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)].amount"
                      :price="scope.row.paymentCollections[getIndexByField(item.field, scope.row.paymentCollections)].amount"
                    />
                  </div>
                  <div v-else>--</div>
                </template>
              </u-table-column>
            </u-table>
            <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
          </div>
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :small="true"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
          <fixed-pagination>
            <template v-if="showMobilePage">
              <FilterInput ref="filterInput" v-model="paramsData" :drawer-size="800" :filter-list="filterList" show-mobile-icon show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" />
              <createBtn v-if="hasRouteAuth('crm:return:create')" text="重设报表" mobile-table @click.native="handleReset"/>
              <btnGroup
                ref="btnGroupRef"
                :list="[
                  { label:'导出', exportApi:'admin/return/detail/export', exportName:'导出回款报表', beforeExport: beforeExport, type: 'export' },
                ]"
                style="height: 36px; margin-left: 8px;"
              />
            </template>
            <template v-else>
              <div class="pagi-container">
                <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
              </div>
              <el-pagination
                v-show="list.total > 0"
                :current-page="list.page"
                :page-size="list.perPage"
                :total="list.total"
                :page-sizes="[20, 50, 100, 250, 500]"
                :layout="showMobilePage?pageLayout:'total, prev, pager, next, sizes, jumper'"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </template>
          </fixed-pagination>
        </div>
        <ReportsCommonDialog ref="reportsCommonDialogRef" />
      </div>
      <div v-else class="default-content">
        <div v-if="showMobilePage" class="flex mobile-header">
          <div style="flex: 1;"/>
          <ListHeader />
        </div>
        <empty-placeholder :text="renderText[status]" style="min-height: calc(100vh - 80px);background-color: #f5f5f5" />
        <el-button
          v-if="hasRouteAuth('crm:return:create') && status === 2"
          size="small"
          type="primary"
          style="margin-top: 16px;"
          @click="handleReset">
          重设报表
        </el-button>
      </div>
    </template>
    <rangeDialog ref="resetRange" is-reset @submit="handleSubmit" />
  </div>
</template>

<script>
import TableAdaptive from '@/mixins/tableAdaptive';
import TableSelections from '@/mixins/tableSelections';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import rangeDialog from '../components/rangeDialog';
import ReportsCommonDialog from '@/components/reportsCommonDialog';
import createBtn from '@/components/Common/baseComponent/createBtn';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { getReturnStatistics, getReturnDetailList, getDynamicTitle, resetReturnReport, getReturnReportList } from '@/api/customer';
import { clientStatusFilter, returnTypeStatus } from '@/filters/status';
import { standardFormatMonth } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import mobileTable from '@/mixins/mobileTable';
import ListHeader from '@/components/Common/header/listHeader';
import icon_24 from '@/assets/dataDisplay/icon_24.png';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import icon_21 from '@/assets/dataDisplay/icon_21.png';
import icon_23 from '@/assets/dataDisplay/icon_23.png';
import icon_7 from '@/assets/dataDisplay/icon_7.png';
// util
import math from '@/utils/math';

export default {
  filters: {
    clientStatusFilter,
    returnTypeStatus,
    standardFormatMonth
  },
  components: {
    EmptyPlaceholder,
    dataDisplay,
    btnGroup,
    rangeDialog,
    ReportsCommonDialog,
    ListHeader,
    createBtn
  },
  mixins: [TableAdaptive, TableSelections, mobileTable],
  data() {
    return {
      status: null,
      returnId: null,
      page: 1,
      perPage: 20,
      isUmyTable: true,
      returnType: null,
      columnList: [], // Table列名
      salesList: [], // 销售列表
      detailData: {}, // 列表参数数据
      returnData: {},
      sortName: '',
      sortType: '',
      idKey: 'id',
      list: {
        items: [],
        isInit: true,
        page: 1,
        perPage: 20,
        total: 0
      },
      tableRefName: 'customerTableRef',
      paramsData: {},
      loading: false,
      dataLoading: false,
      selectedData: [],
      typeOption: [
        { value: 0, label: '公司' },
        { value: 1, label: '个人' }
      ],
      rangeKeyArr: [
        { attr: 'tradeAmount', start: 'tradeAmountStart', end: 'tradeAmountEnd', type: 'moneyFixed' },
        { attr: 'writeOffAmount', start: 'writeOffAmountStart', end: 'writeOffAmountEnd', type: 'moneyFixed' },
        { attr: 'writeOffFlow', start: 'writeOffFlowStart', end: 'writeOffFlowEnd', type: 'moneyFixed' },
        { attr: 'overdraftAmount', start: 'overdraftAmountStart', end: 'overdraftAmountEnd', type: 'moneyFixed' },
        { attr: 'thirdPartyPaymentWriteOff', start: 'thirdPartyPaymentWriteOffStart', end: 'thirdPartyPaymentWriteOffEnd', type: 'moneyFixed' },
        { attr: 'personalWriteOffCompany', start: 'personalWriteOffCompanyStart', end: 'personalWriteOffCompanyEnd', type: 'moneyFixed' },
        { attr: 'toWriteOffAmount', start: 'toWriteOffAmountStart', end: 'toWriteOffAmountEnd', type: 'moneyFixed' }
      ],
      renderText: {
        0: '报表生成中，请稍候查看',
        2: '数据生成失败，请换个条件试试'
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    dataList() {
      const { returnData } = this;
      let amount = math.subtract(returnData['tradeAmount'] || 0, returnData['writeOffAmount'] || 0);
      amount = math.subtract(amount, returnData['writeOffFlow'] || 0);
      return [
        { label: '交易总额', data: returnData['tradeAmount'], tooltip: '统计所选【订单封账月份】的订单总含税金额', isCanFilter: false, icon: icon_7 },
        { label: '核销总额', data: returnData['writeOffAmount'], tooltip: '统计所选【订单封账月份】的订单所关联的核销记录，且核销记录的到账日期及封账月份在【流水到账月份】及【核销封账月份】所选范围内', isCanFilter: false, icon: icon_24 },
        { label: '可核销流水', data: returnData['writeOffFlow'], tooltip: '统计所选【流水到账月份】，流水付款人名称与当前客户一致的流水总金额', isCanFilter: false, icon: icon_17 },
        { label: '待核销金额', data: returnData['waitingForWriteOff'], tooltip: '统计所选【订单封账月份】的订单含税金额-已核销金额（已核销金额满足【流水到账月份】及【核销封账月份】）', isCanFilter: false, icon: icon_23 },
        { label: '欠款金额', data: amount, tooltip: '欠款金额 = 交易总额-核销总额-可核销流水', isCanFilter: false, icon: icon_21 }
      ];
    },
    filterList() {
      return [
        { keyword: 'customerId', name: '编号', type: 'input', labelWidth: '110px' },
        { keyword: 'clientName', name: '客户名称', type: 'input', labelWidth: '110px' },
        { keyword: 'sale', name: '销售', type: 'input', labelWidth: '110px' },
        { keyword: 'tradeAmount', name: '交易总额', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'writeOffAmount', name: '核销总额', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'writeOffFlow', name: '可核销流水', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'overdraftAmount', name: '欠款金额', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'thirdPartyPaymentWriteOff', name: '第三方代付核销', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'personalWriteOffCompany', name: '个人核销公司', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'toWriteOffAmount', name: '待核销金额', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '110px' },
        { keyword: 'customerType', name: '客户类型', type: 'select', options: this.typeOption }
      ];
    },
    tableOutsideHeight() {
      return JSON.stringify(this.paramsData) === '{}' ? 308 : 348;
    }
  },
  created() {
    this.init();
  },
  methods: {
    hasRouteAuth,
    init() {
      this.returnType = Number(sessionStorage.getItem('returnType'));
      this.returnId = Number(this.$route.params.returnId);
      this.getReturnReportList(this.returnId);
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsData));
      paramsRangeFormat(this.rangeKeyArr, params);
      const pageParams = { ... params };
      pageParams.page = this.page;
      pageParams.perPage = this.perPage;
      if (this.sortName) {
        pageParams.sortName = this.sortName;
      }
      if (this.sortType) {
        pageParams.sortType = this.sortType;
      }
      this.getStatistics(params);
      this.getColumnList(params);
      this.getDetailList(pageParams);
    },
    // 拿回款列表参数
    getReturnReportList(id) {
      const params = {};
      params.id = id;
      params.page = this.page;
      params.perPage = this.perPage;
      getReturnReportList(params).then(res => {
        if (res.code === 200 && res.data.items.length) {
          this.detailData = res.data.items[0];
          this.status = res.data.items[0].status;
          this.returnType = res.data.items[0].returnType;
          this.fetchData(true);
        }
      }).catch(err => {
        this.$message.error(err.message);
      });
    },
    getIndexByField(field, array) {
      let index;
      array.map((it, idx) => {
        if (it.field === field) {
          index = idx;
          return;
        }
      });
      return index;
    },
    // 排序字段
    sortableValue(v) {
      const sortableMap = ['tradeAmount', 'writeOffAmount', 'writeOffFlow', 'owePrice', 'thirdPartyPaymentWriteOff', 'personalWriteOffCompany', 'waitingForWriteOff'];
      return sortableMap.includes(v) ? 'custom' : false;
    },
    getWidth(v) {
      return v.length > 8 ? v.length * 18 : null;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    toCustomer(row) {
      const url = this.$router.resolve({
        name: 'detailCustomer',
        params: { customerId: row.customerId }
      });
      window.open(url.href, '_blank');
    },
    getStatistics(params) {
      this.dataLoading = true;
      getReturnStatistics(this.returnId, params).then(res => {
        if (res.code === 200 && res.data) {
          this.returnData = res.data;
          this.dataLoading = false;
        }
      }, _ => {
        this.dataLoading = false;
      }).catch(err => {
        this.$message.error(err.message);
      });
    },
    getDetailList(params) {
      this.loading = true;
      getReturnDetailList(this.returnId, params).then(({ data }) => {
        this.list = data;
        this.loading = false;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }, _ => {
        this.loading = false;
      }).catch(err => {
        this.$message.error(err.message);
      });
    },
    getColumnList(params) {
      getDynamicTitle(this.returnId, params).then(res => {
        if (res.code === 200 && res.data) {
          this.columnList = res.data;
        }
      }).catch(err => {
        this.$message.error(err.message);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsData = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    tableSelectionChange(val) {
      this.selectedData = val;
    },
    beforeExport() {
      const params = JSON.parse(JSON.stringify(this.paramsData));
      paramsRangeFormat(this.rangeKeyArr, params);
      params.reportId = this.returnId;
      if (this.selectedData.length) {
        params.ids = this.selectedData.map(it => it.id).join(',');
      }
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params);
      }
    },
    handleReset() {
      localStorage.setItem('returnData', JSON.stringify(this.detailData));
      this.$refs.resetRange.openDialog();
    },
    handleSubmit(val) {
      const params = val;
      params.id = this.returnId;
      resetReturnReport(params).then(res => {
        if (res.code === 200) {
          this.$refs.resetRange.handleClose();
          this.$message.success('操作成功');
          this.init();
        }
      }, result => {
        this.$message.error(result.message);
        this.$refs.resetRange.cancelLoading();
      }).catch(err => {
        this.$message.error(err.message);
      });
    },
    // 明细弹窗
    showDetail(id, data) {
      const { returnType, field } = data;
      if (field === 'owePrice' || data.amount === 0) return; // 排除欠款金额
      this.$refs['reportsCommonDialogRef'].init(id, returnType, field);
    }
  }
};
</script>

<style lang="scss" scoped>
.mobile-detail-wrap {
  margin: 60px 12px 64px !important;
  .mobile-operate {
    display: flex;
    align-items: center;
    margin-top: 12px;
  }
  .flex {
    display: flex;
  }
  .info-item-title {
    display: inline-block;
    width: 100px;
  }
  .mobile-header {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1001;
    width: 100%;
    background-color: #406EFF !important;
    .mobile-text, .title {
      color: #fff !important;
    }
  }
}
.customer {
.detail-top-container {
  display: flex;
  align-items: center;
  width: 100%;
  background-color: #fff;
  padding: 0 32px;
  height: 48px;
  .title {
    font-size: 16px;
    line-height: 1.5;
    font-family: PingFang SC;
    color: #333333;
  }
}
  .return-detail {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    &::v-deep {
      .el-col-3 {
        width: 20%;
      }
    }
    .detail-info {
      font-size: 14px;
      margin-top: -8px;
      padding-bottom: 8px;
      .detail-info-item {
        .info-item-title {
          color: #999999;
        }
      }
    }
  }
  .pagi-container {
    flex:1;
    height: 32px;
    display: flex;
    align-items: center;
  }
  .link {
    color: #406eff;
    cursor: pointer;
  }
}
.default-content {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column nowrap;
}
</style>
